#######################################################################
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# Openfuyao is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
#######################################################################

import argparse
import logging
import re

from kubernetes import client, config

# 默认参数
NAMESPACE = "default"  # 命名空间
DEFAULT_LABEL = "app=occupie-cpu-task"  # 默认标签

config.load_kube_config()
apps_v1 = client.AppsV1Api()

logging.basicConfig(
    level=logging.INFO,
    format="%(levelname)s: %(message)s",
)


def validate_label(label):
    if not re.fullmatch(r"[a-zA-Z0-9_-]+=[a-zA-Z0-9_-]+", label):
        raise ValueError(f"错误: 标签格式 '{label}' 必须为 key=value")
    return label


def delete_temp_task(namespace, label):
    label = validate_label(label)
    logging.info(f"正在删除命名空间 {namespace} 中标签为 {label} 的Deployment...")
    try:
        deployments = apps_v1.list_namespaced_deployment(
            namespace, label_selector=label
        )
        if not deployments.items:
            logging.error("没有找到匹配的Deployment")
            return
        for deploy in deployments.items:
            apps_v1.delete_namespaced_deployment(deploy.metadata.name, namespace)
            logging.info(f"成功删除Deployment: {deploy.metadata.name}")
    except Exception as e:
        raise RuntimeError(f"删除失败: {e}") from e


def main():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument(
        "-l",
        "--label",
        default=DEFAULT_LABEL,
        help="删除匹配此标签的Deployment（格式: key=value）",
    )
    parser.add_argument(
        "-ns",
        "--namespace",
        default=NAMESPACE,
        help="命名空间",
    )

    args = parser.parse_args()
    delete_temp_task(args.namespace, args.label)


if __name__ == "__main__":
    main()
